package fr.lille.inria.adam.lifl.EcoGardeInventory.Activities;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import fr.lille.inria.adam.lifl.EcoGardeInventory.R;
import fr.lille.inria.adam.lifl.EcoGardeInventory.Services.LocationService;
import fr.lille.inria.adam.lifl.EcoGardeInventory.Services.LocationService.LocationServiceBinder;
import fr.lille.inria.adam.lifl.EcoGardeInventory.Utils.EspeceEntry;
import fr.lille.inria.adam.lifl.EcoGardeInventory.Utils.SIGObservation;

public class Finalize extends BuildObservationActivity {
	protected ServiceConnection clientLocationServConn = null;
	protected boolean isClientLocationBounded = false;
	private final static int ON_TAKE_PHOTO_RESULT_CODE = 0x01;
	public static final DateFormat photoDateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.FRANCE);
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.finalisation);
		this.setTitle("Récapitulatif (X/X)");
		
		this.initializeLocationServConn();
		
		final EditText noteField = (EditText) findViewById(R.id.noteTextuelle_editText);
		final Button sendButton = (Button) this.findViewById(R.id.sendButton);
		sendButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				observationEnCoursDeRealisation.noteTextuelle = noteField.getText().toString();
				clientBinder.sendNewObservation(observationEnCoursDeRealisation);
				finish();
			}
		});
		
		final Button photoButton = (Button) this.findViewById(R.id.takePhotoButton);
		photoButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				final Uri photoUri = Uri.fromFile(Finalize.getOutputPhotoFile());
				observationEnCoursDeRealisation.photoUri = photoUri.toString();
				takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
				startActivityForResult(takePictureIntent, ON_TAKE_PHOTO_RESULT_CODE);
			}
		});
	}
	
	@Override
	protected void onStart() {
		super.onStart();
		
		Intent locServIntent = new Intent(this, LocationService.class);
		isClientLocationBounded = bindService(locServIntent, this.clientLocationServConn, BIND_AUTO_CREATE);
		observationEnCoursDeRealisation.timestamp = System.currentTimeMillis();
	}
	
	
	@Override
	protected void onStop() {
		super.onStop();
		if (isClientLocationBounded) { unbindService(clientLocationServConn); }
	}
	
	/**Founi un fichier où écrire une photo
	 * @return
	 */
	private static File getOutputPhotoFile() {
		File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "moano-inventaire");
		if (! mediaStorageDir.exists()) mediaStorageDir.mkdirs();
		
		File photoFile = new File(mediaStorageDir.getPath(), "IMG_"+photoDateFormat.format(Calendar.getInstance().getTime())+".jpg");
		return photoFile;
	}

	/**Binder les données avec la vue
	 */
	private void initializeTextViews() {
		// On récupére les TextView
		final TextView obsText = (TextView) findViewById(R.id.finalisation_observateur_textView);
		final TextView recText = (TextView) findViewById(R.id.finalisation_recensement_textView);
		final TextView grpText = (TextView) findViewById(R.id.finalisation_groupe_textView);
		final TextView espText = (TextView) findViewById(R.id.finalisation_espece_textView);
		final TextView qtText = (TextView) findViewById(R.id.finalisation_quantite_textView);
		final TextView precText = (TextView) findViewById(R.id.finalisation_precision_textView);
		final TextView sexeText = (TextView) findViewById(R.id.finalisation_sexe_textView);
		final TextView compText = (TextView) findViewById(R.id.finalisation_comportement_textView);
		final TextView positionText = (TextView) findViewById(R.id.finalisation_position_textView);
		
		// Dans l'observation on enregistre juste les clefs
		// donc on récupére les noms
		SIGObservation o = observationEnCoursDeRealisation;
		final String obsName = clientBinder.getObservateurName(o.observateur);
		final String recName = clientBinder.getRecensementName(o.recensement);
		final String grpName = clientBinder.getGroupeEspeceName(o.groupeEspece);
		final EspeceEntry espece = clientBinder.getEspeceEntry(o.nomEspece);
		final String precName = clientBinder.getPrecisionName(o.populationSizePrecision);
		final String sexeName = getString(o.populationGender.ressourceId);
		final String compName = clientBinder.getComportementName(o.comportement);
		
		// et on bind
		final Location currentLocation = observationEnCoursDeRealisation.location;
		obsText.setText(getString(R.string.finalisation_observateur, obsName));
		recText.setText(getString(R.string.finalisation_recensement, recName));
		grpText.setText(getString(R.string.finalisation_groupe, grpName));
		espText.setText(getString(R.string.finalisation_espece, espece.commun));
		qtText.setText(getString(R.string.finalisation_quantite, o.populationSize));
		precText.setText(getString(R.string.finalisation_precision, precName));
		sexeText.setText(getString(R.string.finalisation_sexe, sexeName));
		compText.setText(getString(R.string.finalisation_comportement, compName));
		positionText.setText(getString(R.string.finalisation_position, 
				currentLocation.getLatitude(), 
				currentLocation.getLongitude(),
				currentLocation.getAccuracy()));
	}
	
	@Override
	protected ServiceConnection initializeClientSIGServConn() {
		return new ServiceConnection() {
			
			@Override
			public void onServiceDisconnected(ComponentName name) { }
			
			@Override
			public void onServiceConnected(ComponentName name, IBinder service) {
				initializeTextViews();
			}
		};
	}
	
	/**Connexion au GéoLoc Service
	 */
	private void initializeLocationServConn() {
		/* Pour cette derniére Activité, nous allons pousser le service 
		 * localisation au maximum. On va aussi ajouter un écouteur au service 
		 * de localisation pour actualiser la vue é chaque qu'une meilleure
		 * localisation est fournie.
		 */
		this.clientLocationServConn = new ServiceConnection() {
			@Override
			public void onServiceDisconnected(ComponentName name) { }
			
			@Override
			public void onServiceConnected(ComponentName name, IBinder service) {
				final LocationServiceBinder bind = (LocationServiceBinder) service;
				bind.registerLocationUpdates(new Messenger(new OnLocHandler()));
				observationEnCoursDeRealisation.location = bind.getBestLocation();
				initializeTextViews();
				
				bind.turnRealTime();
			}
		};
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case ON_TAKE_PHOTO_RESULT_CODE:
			switch (resultCode) {
			case RESULT_OK:
				Toast.makeText(this, "Photo ajoutée", Toast.LENGTH_SHORT).show();
				//observationEnCoursDeRealisation.photoUri a été parametre au moment du click sur "Ajout photo"
				break;
			case RESULT_CANCELED:
				observationEnCoursDeRealisation.photoUri = "";
				Toast.makeText(this, "Ajout de la photo interrompu", Toast.LENGTH_SHORT).show();
				break;
			}
			break;

		default:
			Log.wtf("Finalize", "onActivityResult requestCode impossible: "+requestCode);
			break;
		}
	}
	
	private class OnLocHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			observationEnCoursDeRealisation.location = (Location) msg.obj;
			initializeTextViews();
		}
	}
}
